package com.love.marriage.matchmakerInfo.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.marriage.matchmakerInfo.dto.MatchmakerInfoExportDto;
import com.love.marriage.matchmakerInfo.entity.MatchmakerInfo;
import com.love.marriage.matchmakerInfo.mapper.MatchmakerInfoMapper;
import com.love.marriage.matchmakerInfo.service.MatchmakerInfoService;
import com.love.marriage.matchmakerInfo.vo.MatchmakerInfoVo;
import com.love.marriage.oss.service.FileInfoService;
import com.love.marriage.oss.vo.FileInfoVo;
import com.love.marriage.userInfo.mapper.UserInfoMapper;
import com.love.marriage.userInfo.vo.UserInfoVo;
import com.love.marriage.userMembershipInfo.service.UserMemberPrivilegeService;
import com.love.marriage.userProfileInfo.mapper.UserProfileInfoMapper;
import com.love.marriage.userProfileInfo.vo.UserProfileInfoVo;
import com.love.marriage.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * description:  红娘信息表服务实现类
 * author:       alex
 * createDate:   2024-11-05 22:09:26
 * version:      1.0.0
 */
@Service
@RequiredArgsConstructor
public class MatchmakerInfoServiceImp extends ServiceImpl<MatchmakerInfoMapper, MatchmakerInfo> implements MatchmakerInfoService {

    private final MatchmakerInfoMapper matchmakerInfoMapper;

    private final FileInfoService fileInfoService;

    private final UserProfileInfoMapper userProfileInfoMapper;

    private final UserInfoMapper userInfoMapper;

    private final UserMemberPrivilegeService userMemberPrivilegeService;

    @Override
    public Page<MatchmakerInfoVo> getPage(Long pageNum, Long pageSize, MatchmakerInfoVo matchmakerInfoVo) {
        Page<MatchmakerInfoVo> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        Page<MatchmakerInfoVo> res = matchmakerInfoMapper.getPage(page, matchmakerInfoVo);
        if (res != null && res.getRecords() != null && res.getRecords().size() > 0) {
            res.getRecords().forEach(this::getFile);
        }
        return res;
    }

    @Override
    public MatchmakerInfoVo queryMatchmakerInfo(Long id) {
        MatchmakerInfoVo matchmakerInfoVo = matchmakerInfoMapper.queryMatchmakerInfo(id);
        getFile(matchmakerInfoVo);
        return matchmakerInfoVo;
    }

    @Override
    public MatchmakerInfoVo queryByUserId(Long userId) {
        MatchmakerInfoVo matchmakerInfoVo = matchmakerInfoMapper.queryMatchmakerInfoByUserId(userId);
        getFile(matchmakerInfoVo);
        return matchmakerInfoVo;
    }

    @Override
    public MatchmakerInfoVo queryNewMatchmakerByUserId(Long userId) {
        MatchmakerInfoVo matchmakerInfoVo = matchmakerInfoMapper.queryMatchmakerInfoByUserId(userId);
        // 如果数据不存在，则从个人档案中获取数据
        if (matchmakerInfoVo == null) {
            matchmakerInfoVo = new MatchmakerInfoVo();
            UserProfileInfoVo dbProfile = userProfileInfoMapper.queryUserProfileInfoByUserId(userId);
            if (dbProfile != null) {
                matchmakerInfoVo.setName(dbProfile.getNickname());
                matchmakerInfoVo.setGender(dbProfile.getGender());
                matchmakerInfoVo.setBirthDate(dbProfile.getBirthYearMonth());
                matchmakerInfoVo.setContactPhone(dbProfile.getContactPhone());
                matchmakerInfoVo.setProvinceId(dbProfile.getProvinceId());
                matchmakerInfoVo.setProvinceName(dbProfile.getProvinceName());
                matchmakerInfoVo.setCityId(dbProfile.getCityId());
                matchmakerInfoVo.setCityName(dbProfile.getCityName());
                matchmakerInfoVo.setDistrictId(dbProfile.getDistrictId());
                matchmakerInfoVo.setDistrictName(dbProfile.getDistrictName());
            }
            UserInfoVo userInfoVo = userInfoMapper.queryUserInfo(userId);
            if (userInfoVo != null && userInfoVo.getAvatar() != null) {
                try {
                    FileInfoVo fileInfoVo = fileInfoService.queryFileInfo(userInfoVo.getAvatar());
                    if (fileInfoVo != null) {
                        matchmakerInfoVo.setPhotoId(userInfoVo.getAvatar());
                        matchmakerInfoVo.setPhotoUrl(fileInfoVo.getPreUrl());
                        matchmakerInfoVo.setPhotoFileInfoVo(fileInfoVo);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            getFile(matchmakerInfoVo);
        }
        return matchmakerInfoVo;
    }

    private void getFile(MatchmakerInfoVo matchmakerInfoVo) {
        if (matchmakerInfoVo != null) {
            if (matchmakerInfoVo.getPhotoId() != null) {
                FileInfoVo fileInfoVo = null;
                try {
                    fileInfoVo = fileInfoService.queryFileInfo(matchmakerInfoVo.getPhotoId());
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                if (fileInfoVo != null) {
                    matchmakerInfoVo.setPhotoUrl(fileInfoVo.getPreUrl());
                    matchmakerInfoVo.setPhotoFileInfoVo(fileInfoVo);
                }
            }
            if (matchmakerInfoVo.getWechatQrcodeId() != null) {
                FileInfoVo fileInfoVo = null;
                try {
                    fileInfoVo = fileInfoService.queryFileInfo(matchmakerInfoVo.getWechatQrcodeId());
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                if (fileInfoVo != null) {
                    matchmakerInfoVo.setWechatQrcodeUrl(fileInfoVo.getPreUrl());
                    matchmakerInfoVo.setWechatQrcodeFileInfoVo(fileInfoVo);
                }
            }
        }
    }

    @Override
    public MatchmakerInfoVo addMatchmakerInfo(MatchmakerInfoVo matchmakerInfoVo) {
        MatchmakerInfo matchmakerInfo = new MatchmakerInfo();
        BeanUtils.copyProperties(matchmakerInfoVo, matchmakerInfo);
        Integer maxNo = matchmakerInfoMapper.getMaxNo();
        if (maxNo == null) {
            maxNo = 100;
        }
        matchmakerInfo.setNo(maxNo + 1);
        matchmakerInfoMapper.insert(matchmakerInfo);
        MatchmakerInfoVo res = new MatchmakerInfoVo();
        BeanUtils.copyProperties(matchmakerInfo, res);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MatchmakerInfoVo addInfo(MatchmakerInfoVo matchmakerInfoVo) throws Exception {
        // 查询是否维护用户档案信息
//        UserProfileInfoVo dbProfile = userProfileInfoMapper.queryUserProfileInfoByUserId(matchmakerInfoVo.getUserId());
//        if (dbProfile != null && StringUtils.isNotBlank(dbProfile.getNickname())) {
//            throw new Exception("用户档案已维护，不能添加红娘信息");
//        }
        // 如果照片为空，则从当前人的头像中获取
        if (matchmakerInfoVo.getPhotoId() == null) {
            UserInfoVo dbUser = userInfoMapper.queryUserInfo(matchmakerInfoVo.getUserId());
            if (dbUser != null && dbUser.getAvatar() != null) {
                matchmakerInfoVo.setPhotoId(dbUser.getAvatar());
            }
        }
        MatchmakerInfoVo matchmakerInfoVo1 = queryByUserId(matchmakerInfoVo.getUserId());
        MatchmakerInfoVo res;
        if (matchmakerInfoVo1 == null) {
            res = addMatchmakerInfo(matchmakerInfoVo);
        } else {
            matchmakerInfoVo.setId(matchmakerInfoVo1.getId());
            res = updateMatchmakerInfo(matchmakerInfoVo);
        }
        // 添加会员、红娘、合伙人相关权益
        userMemberPrivilegeService.addMemberPrivilege(matchmakerInfoVo.getUserId());
        return res;
    }

    @Override
    public MatchmakerInfoVo updateMatchmakerInfo(MatchmakerInfoVo matchmakerInfoVo) {
        MatchmakerInfo matchmakerInfo = new MatchmakerInfo();
        BeanUtils.copyProperties(matchmakerInfoVo, matchmakerInfo);
        matchmakerInfoMapper.updateById(matchmakerInfo);
        return matchmakerInfoVo;
    }

    @Override
    public Boolean deleteMatchmakerInfo(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return true;
        }
        List<String> idArr = Arrays.asList(ids.split(","));
        matchmakerInfoMapper.deleteBatchIds(idArr);
        return true;
    }

    @Override
    public void exportMatchmakerInfo(MatchmakerInfoVo matchmakerInfoVo, HttpServletResponse response) throws Exception {
        // 查询所有红娘数据
        List<MatchmakerInfoVo> dataList = matchmakerInfoMapper.getList(matchmakerInfoVo);
        
        // 填充文件信息
        if (dataList != null && !dataList.isEmpty()) {
            dataList.forEach(this::getFile);
        }

        // 转换为导出DTO
        List<MatchmakerInfoExportDto> exportList = convertToExportDto(dataList);

        // 设置导出参数
        ExportParams exportParams = new ExportParams("红娘信息", "红娘信息");
        exportParams.setCreateHeadRows(true);

        // 使用EasyPoi生成Excel
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, MatchmakerInfoExportDto.class, exportList);

        // 设置响应头
        String fileName = "红娘信息_" + System.currentTimeMillis() + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 写入响应流
        try {
            workbook.write(response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("导出红娘信息失败", e);
            throw new Exception("导出失败: " + e.getMessage());
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                log.error("关闭工作簿失败", e);
            }
        }
    }

    /**
     * 转换为导出DTO
     */
    private List<MatchmakerInfoExportDto> convertToExportDto(List<MatchmakerInfoVo> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
        }
        List<MatchmakerInfoExportDto> exportList = new ArrayList<>();

        for (MatchmakerInfoVo data : dataList) {
            MatchmakerInfoExportDto exportDto = new MatchmakerInfoExportDto();
            // 编号
            exportDto.setNo(data.getNo() != null ? data.getNo().toString() : "");
            // 姓名
            exportDto.setName(data.getName() != null ? data.getName() : "");
            // 性别
            String genderText = "";
            if ("0".equals(data.getGender())) {
                genderText = "男";
            } else if ("1".equals(data.getGender())) {
                genderText = "女";
            }
            exportDto.setGender(genderText);
            // 出生日期 - 转换为Date类型
            if (data.getBirthDate() != null) {
                exportDto.setBirthDate(java.sql.Date.valueOf(data.getBirthDate()));
            }
            // 联系电话
            exportDto.setContactPhone(data.getContactPhone() != null ? data.getContactPhone() : "");
            // 省份
            exportDto.setProvinceName(data.getProvinceName() != null ? data.getProvinceName() : "");
            // 城市
            exportDto.setCityName(data.getCityName() != null ? data.getCityName() : "");
            // 区县
            exportDto.setDistrictName(data.getDistrictName() != null ? data.getDistrictName() : "");
            // 入职日期 - 转换为Date类型
            if (data.getEntryDate() != null) {
                exportDto.setEntryDate(java.sql.Date.valueOf(data.getEntryDate()));
            }
            // 擅长领域
            exportDto.setExpertise(data.getExpertise() != null ? data.getExpertise() : "");
            // 职级
            exportDto.setPositionLevelName(data.getPositionLevelName() != null ? data.getPositionLevelName() : "");
            // 状态
            String statusText = "";
            if (data.getStatus() != null) {
                switch (data.getStatus()) {
                    case 1:
                        statusText = "审批中";
                        break;
                    case 2:
                        statusText = "审批通过";
                        break;
                    default:
                        statusText = "未知";
                        break;
                }
            }
            exportDto.setStatus(statusText);
            // 用户编码
            exportDto.setCode(data.getCode() != null ? data.getCode() : "");
            // 单身标识
            exportDto.setSingleFlag(data.getSingleFlag() != null &&  data.getSingleFlag() ? "是" : "否");
            exportList.add(exportDto);
        }
        
        return exportList;
    }
}
